package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.domain.IotMsgService;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 设备管理信息表Service业务层处理
 * 
 * @author zsn
 * @date 2025-05-26
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 查询设备管理信息表
     * 
     * @param id 设备管理信息表主键
     * @return 设备管理信息表
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理信息表列表
     * 
     * @param deviceData 设备管理信息表
     * @return 设备管理信息表
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备管理信息表
     * 
     * @param deviceData 设备管理信息表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备管理信息表
     * 
     * @param deviceData 设备管理信息表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }


    /**
     * 批量删除设备管理信息表
     * 
     * @param ids 需要删除的设备管理信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息表信息
     * 
     * @param id 设备管理信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 基于IOT设备上传通知的数据，批量保存设备数据
     *
     * @param contentStr
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMessage(String contentStr) {
        //1.判断设备是否存在
        if (StringUtils.isBlank(contentStr)){
            throw new BaseException("设备为空");
        }

        JSONObject message = JSONUtil.parseObj(contentStr);
        JSONObject notifyData = message.getJSONObject("notify_data");
        if (notifyData==null){
            throw new BaseException("设备为空");
        }

        JSONObject body = notifyData.getJSONObject("body");
        JSONObject header = notifyData.getJSONObject("header");
        if (body==null || header==null){
            throw new BaseException("设备为空");
        }

        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();

        //判断设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device==null){
            throw new BaseException("设备为空");
        }
        //2.设备数据封装
        List<IotMsgService> serviceList = iotMsgNotifyData.getBody().getServices();
        List<DeviceData> deviceDataList = new ArrayList<>();

        serviceList.forEach(x->{
            String eventTimeStr = x.getEventTime();
            LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            Map<String, Object> properties = x.getProperties();
            properties.forEach((k,v)->{
                DeviceData deviceData = new DeviceData();
                BeanUtils.copyProperties(device,deviceData);
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(String.valueOf(v));
                deviceData.setAlarmTime(eventTime);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceDataList.add(deviceData);
            });
            log.info("看我看我:{}",deviceDataList);
        });
        //3.批量保存
        if (CollUtil.isNotEmpty(deviceDataList)){
//            boolean result = this.saveBatch(deviceDataList);
            boolean result = this.saveBatch(deviceDataList);
            if (!result){
                throw new BaseException("批量保存失败");
            }
            log.info("批量保存设备上报数据成功，本地保存成功{}条", deviceDataList.size());
        }

        //4.设备最后一次上报数据更新到缓存中
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId,JSONUtil.toJsonStr(deviceDataList));
    }


    /**
     * 获取设备数据分页结果
     *
     * @param dto
     * @return
     */
    @Override
    public Page listDeviceData(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = this.lambdaQuery().eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null || dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
        return page;
    }
}
